package com.xyebank.ledger.manage;

//import com.xyebank.cw.api.IUserApplyInfoService;
//import com.xyebank.ledger.api.ILedgerApplyService;

import com.xyebank.ledger.conf.MigTaskBean;
import com.xyebank.ledger.service.common.MigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MigDispatcher {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ManageRedisTool redisTool;

    @Autowired
    MigTaskBean migTaskBean;


    /**
     * 全部迁移
     *
     * @return
     */
    public Integer migerateAll() {
        List<MigService> list = migTaskBean.getTaskList();
        if (list == null || list.size() == 0) {
            logger.error("未发现任何迁移任务，请仔细检查！");
            return 0;
        }

        for (int i = 0; i < list.size(); i++) {
            MigService task = list.get(i);
            dispatchWithLock(task.getJobType(), task);
        }
        return 1;
    }


    /**
     * 指定任务类型迁移
     *
     * @param jobType
     * @return
     */
    public Integer dispatch(String jobType) {
        MigService migService = migTaskBean.getMigService(jobType);
        if (migService == null) {
            logger.error("系统异常，为获取到{}对应的dispatcher", jobType);
            return 0;
        }
        dispatchWithLock(jobType, migService);
        return 1;
    }


    /**
     * 1 判断当前任务相关的工作状态
     * 2 调用接口进行迁移
     * 3 迁移完成后　通知更新下标，并修改工作状态
     *
     * @param jobType
     * @param migService
     * @return
     */
    private Integer dispatchWithLock(String jobType, MigService migService) {
        if (!redisTool.setWorkStatus(jobType)) {
            logger.info("当前有其他的任务在执行：{}", jobType);
            canNotInterruptWork(jobType);
            return 0;
        }
        //判断当前的T1任务是否还在处理中
        try {
            redisTool.updateWorkStatus(jobType); //更新锁，让锁有个自动释放时间
            if (redisTool.isT1Working(jobType)) {
                //非常重要的释放锁
                logger.info("当前任务的T1还在执行：{}", jobType);
                redisTool.removeWorkStatus(jobType);
                canNotInterruptWork(jobType);
            } else {
                // 调用接口进行迁移
                logger.info("开始迁移执行。。。。。。。。");
                migService.migrate(); //异步线程
                logger.info("迁移执行结束。。。。。。。。");
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //异常情况下及时释放所　非常重要的
            redisTool.removeWorkStatus(jobType);
        }
        return 0;
    }


    /**
     * //TODO Redis异常如何处理？　貌似可以忽略
     * 不能影响当前正在执行的任务
     */
    private void canNotInterruptWork(String jobType) {
        //更新查询次数 +1
        redisTool.increseQueryCount(jobType);
        //更新操作时间
        redisTool.updateLastDate(jobType);
        //退出当前，等待下次执行
    }


    public void release(String key) {
        redisTool.removeWorkStatus(key);
    }


    /**
     * 指定时间段迁移
     *
     * @param jobType
     * @return
     */
    public Integer dispatch(String jobType, Date dateStart, Date dateEnd) {
        MigService migService = migTaskBean.getMigService(jobType);
        if (migService == null) {
            logger.error("系统异常，为获取到{}对应的dispatcher", jobType);
            return 0;
        }
        migService.migrate(dateStart, dateEnd);
        return 1;
    }
}
